﻿/* HtmlHelper 扩展 by match on 20110425 */
namespace ShopB2C.Core.Extensions {
    using System;
    using System.Reflection;
    using System.Web.Handlers;
    using System.Web.Mvc;
    using System.Web.UI;
    using System.Web.WebPages;
    using ShopB2C.Core.Entities;
    /// <summary>
    /// HtmlHelper 扩展
    /// </summary>
    public static class HtmlExtesions {
        // 缓存 Page 页实例, 为获取资源文件准备
        private static Page _CachedPage = null;
        /// <summary>
        /// 静态构造函数
        /// </summary>
        static HtmlExtesions() {
            _CachedPage = _CachedPage ?? (_CachedPage = new Page());
        }
        /// <summary>
        /// 创建分页
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <param name="pagerParams">分页参数</param>
        public static HelperResult Pager(this HtmlHelper helper, PagerParams pagerParams = null) {
            IBaseViewModel model = helper.ViewData.Model as IBaseViewModel;
            if (pagerParams == null) {
                pagerParams = new PagerParams();
                if (model != null) {
                    pagerParams = model.PagerParams;
                }
            }
            return new HelperResult(writer => {
                pagerParams.TextWriter = writer;
                pagerParams.Execute();
            });
        }
        /// <summary>
        /// 注册分页的 CSS 资源文件
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        public static HelperResult RegisterCssForPager(this HtmlHelper helper) {
            return new HelperResult(writer => {
                string cssUrl = _CachedPage.ClientScript.GetWebResourceUrl(typeof(PagerParams), "ShopB2C.Core.Resources.Pager.css");
                HtmlTextWriter hw = new HtmlTextWriter(writer);

                hw.AddAttribute(HtmlTextWriterAttribute.Href, cssUrl);
                hw.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet");
                hw.AddAttribute(HtmlTextWriterAttribute.Type, "text/css");
                hw.RenderBeginTag(HtmlTextWriterTag.Link);
                hw.RenderEndTag();
            });
        }
        /// <summary>
        /// 注册分页的 JavaScript 资源文件
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        public static HelperResult RegisterJavaScriptForPager(this HtmlHelper helper) {
            return new HelperResult(writer => {
                string jsUrl = _CachedPage.ClientScript.GetWebResourceUrl(typeof(PagerParams), "ShopB2C.Core.Resources.Pager.js");
                HtmlTextWriter hw = new HtmlTextWriter(writer);

                hw.AddAttribute(HtmlTextWriterAttribute.Src, jsUrl);
                hw.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
                hw.RenderBeginTag(HtmlTextWriterTag.Script);
                hw.RenderEndTag();
            });
        }
    }
}
